import 'package:getx_mvvm_lite/core/base/base_view_model.dart';
import 'package:getx_mvvm_lite/core/state/page_state.dart';
import 'package:get/get.dart';

typedef PageFetcher<T> = Future<List<T>> Function(int page, int pageSize);

class ListViewModel<T> extends BaseViewModel {
  final RxList<T> items = <T>[].obs;
  int page = 1;
  int pageSize = 20;
  bool hasMore = true;
  bool isLoadingMore = false;

  final PageFetcher<T> fetcher;

  ListViewModel(this.fetcher);

  Future<void> loadInitial() async {
    setLoading();
    page = 1;
    final list = await safeFetch(page, pageSize);
    items.assignAll(list);
    hasMore = list.length == pageSize;
    if (items.isEmpty) {
      setEmpty('No data');
    } else {
      setContent();
    }
  }

  Future<void> refresh() async {
    await loadInitial();
  }

  Future<void> loadMore() async {
    if (!hasMore || isLoadingMore) return;
    isLoadingMore = true;
    final next = page + 1;
    final list = await safeFetch(next, pageSize);
    if (list.isNotEmpty) {
      items.addAll(list);
      page = next;
      hasMore = list.length == pageSize;
    } else {
      hasMore = false;
    }
    isLoadingMore = false;
  }

  Future<List<T>> safeFetch(int page, int pageSize) async {
    try {
      final res = await fetcher(page, pageSize);
      return res;
    } catch (e) {
      setError(e.toString());
      return [];
    }
  }
}